﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils.Drawing;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Ribbon.ViewInfo;
using SMART_VIET_V01.Lib;
using DevExpress.XtraTab;
using System.Collections;
using System.IO;
using System.Media;
using System.Threading.Tasks;


namespace SMART_VIET_V01
{
    public partial class frm_quanlyMedias : Form
    {
        SQL_Functions sql;
        TreeNode trSelect = null;
        ArrayList listGallary;
        public frm_quanlyMedias()
        {
            listGallary = new ArrayList();
            sql = new SQL_Functions();
            InitializeComponent();
            getlistImg();
            trView.ImageList = imgListTrView;

            loadTieuDe();
            loadTreeView();
            getListImage();
        }

        #region Add TabPage & Gallary
        ArrayList listTabPage;
        public void loadTieuDe()
        {
            listTabPage = new ArrayList();
            string query = "SELECT * FROM tblMediaType";
            DataTable dt = sql.returnDB(query);
            if (dt != null)
            {
                int count = dt.Rows.Count;
                XtraTabPage[] listtab = null;
                for (int i = 0; i < count; i++)
                {
                    XtraTabPage tabPage = new XtraTabPage();
                    tabPage.Text = dt.Rows[i]["ten_loai"].ToString();
                    tabPage.Name = dt.Rows[i]["stt"].ToString();
                    tabPage.Size = new System.Drawing.Size(792, 176);
                    tabPage.Tag = dt.Rows[i]["stt"].ToString();
                    listTabPage.Add(tabPage);
                    tabPage.Controls.Add(loadGallary(dt.Rows[i]["stt"].ToString()));
                    tabControl.TabPages.Add(tabPage);
                }
            }
        }


        public GalleryControl loadGallary(string name)
        {
            //
            GalleryControl glc = new GalleryControl();
            glc.Name = name;
            glc.Dock = System.Windows.Forms.DockStyle.Fill;
            glc.Gallery.ImageSize = new System.Drawing.Size(120, 80);
            glc.Gallery.ShowItemText = true;
            glc.Gallery.ItemImageLayout = DevExpress.Utils.Drawing.ImageLayoutMode.ZoomInside;
            glc.Gallery.UseMaxImageSize = true;
            glc.Gallery.ItemClick += new GalleryItemClickEventHandler(glc_Click);
            glc.Gallery.ItemDoubleClick += new GalleryItemClickEventHandler(glc_DoubleClick);
            listGallary.Add(glc);
            return glc;
        }

        private void glc_Click(object sender, GalleryItemClickEventArgs e)
        {
            if (e.Item.Checked) e.Item.Checked = false;
            else e.Item.Checked = true;
        }
        string fileNameSave = null;
        private void glc_DoubleClick(object sender, GalleryItemClickEventArgs e)
        {
            pnlView.Visible = true;
            string query = "SELECT * FROM tblMedia WHERE stt = " + e.Item.Tag.ToString();
            DataTable dt = sql.returnDB(query);
            if (dt != null)
            {
                string duoi = dt.Rows[0]["duoifile"].ToString();
                int dfile = Helping_Functions.returnFile(duoi);
                Console.WriteLine("----- la file : " + dfile);
                byte[] bytes = (byte[])dt.Rows[0]["media"];
                if (wmdMedia.playState == WMPLib.WMPPlayState.wmppsPlaying) { wmdMedia.Ctlcontrols.stop(); }
                if (dfile == 1)
                {
                    picBox.Visible = true;
                    wmdMedia.Visible = false;
                    Image img = convert(bytes);
                    picBox.Image = img;
                }
                if (dfile > 1)
                {
                    picBox.Visible = false;
                    wmdMedia.Visible = true;
                    wmdMedia.URL = "";
                    using (MemoryStream stream = new MemoryStream(bytes))
                    {
                        if (File.Exists(fileNameSave)) File.Delete(fileNameSave);
                        fileNameSave = @"temp." + duoi;
                        SaveMemoryStream(stream, fileNameSave);
                        wmdMedia.URL = fileNameSave;
                        wmdMedia.Ctlcontrols.play();
                    }
                }

            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (wmdMedia.playState == WMPLib.WMPPlayState.wmppsPlaying) { wmdMedia.Ctlcontrols.stop(); }
            pnlView.Visible = false;
        }
        public void SaveMemoryStream(MemoryStream ms, string FileName)
        {

            if (File.Exists(FileName)) File.Delete(FileName);
            FileStream outStream = File.OpenWrite(FileName);
            ms.WriteTo(outStream);
            outStream.Flush();
            outStream.Close();
        }
        #endregion

        #region add TreeView
        public void loadTreeView()
        {
            trView.SelectedImageIndex = 3;
            trView.Nodes.Clear();
            string query = "SELECT kl.stt As klID, kl.ten_khoilop as klTen, mh.stt As mhID, mh.ten_monhoc as mhTen,ml.stt as mlID,ml.ten_chuyende as mlTen FROM tblKhoiLop kl LEFT JOIN (tblMonHoc mh LEFT JOIN tblMediaLib ml ON mh.stt = ml.monhoc_id) ON kl.stt = mh.khoilop_id";
            DataTable dt = sql.returnDB(query);
            if (dt != null)
            {
                int count = dt.Rows.Count;
                Console.WriteLine(count.ToString());
                TreeNode trNodeLv0 = null;
                TreeNode trNodeLv1 = null;
                for (int i = 0; i < count; i++)
                {
                    DataRow dr = dt.Rows[i];
                    if (i == 0) { trNodeLv0 = addNode(dr["klID"].ToString(), dr["klTen"].ToString(), 0); trView.Nodes.Add(trNodeLv0); }
                    else
                    {
                        if (trNodeLv0.Name.ToString() != dr["klID"].ToString()) { trNodeLv0 = addNode(dr["klID"].ToString(), dr["klTen"].ToString(), 0); trView.Nodes.Add(trNodeLv0); }
                    }
                    if (!string.IsNullOrEmpty(dr["mhID"].ToString()))
                    {
                        if (trNodeLv1 == null)
                        {
                            trNodeLv1 = addNode(dr["mhID"].ToString(), dr["mhTen"].ToString(), 1);
                            trNodeLv0.Nodes.Add(trNodeLv1);

                        }
                        else if (trNodeLv1.Name.ToString() != dt.Rows[i]["mhID"].ToString())
                        {
                            trNodeLv1 = addNode(dr["mhID"].ToString(), dr["mhTen"].ToString(), 1);
                            trNodeLv0.Nodes.Add(trNodeLv1);
                        }
                    }
                    if (!string.IsNullOrEmpty(dr["mlID"].ToString())) trNodeLv1.Nodes.Add(addNode(dr["mlID"].ToString(), dr["mlTen"].ToString(), 2));
                }
            }

        }
        public void getlistImg()
        {
            Image img = global::SMART_VIET_V01.Properties.Resources.quanlyMedia_lv0;
            Image img2 = global::SMART_VIET_V01.Properties.Resources.quanlyMedia_lv1;
            Image img3 = global::SMART_VIET_V01.Properties.Resources.quanlyMedia_lv2;
            Image img4 = global::SMART_VIET_V01.Properties.Resources.quanlyMedia_selected;
            imgListTrView.Images.AddRange(new Image[] { img, img2, img3, img4 });
        }
        public TreeNode addNode(string _name, string _caption, int _lv, TreeNode _beforNode = null)
        {

            TreeNode trNode = new TreeNode(_caption);
            trNode.Name = _name;
            trNode.ImageIndex = _lv;

            if (_beforNode != null) { _beforNode.Nodes.Add(trNode); return _beforNode; }
            else return trNode;
        }
        private void trView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            button1_Click(null, null);
            resetAlbum();
            ArrayList listMediaLib = new ArrayList();
            TreeNode checkNode = trView.SelectedNode;
            if (checkNode.Level == 0)
            {
                int coLv1 = checkNode.Nodes.Count;
                foreach (TreeNode node in checkNode.Nodes)
                {
                    foreach (TreeNode node2 in node.Nodes) listMediaLib.Add(node2.Name.ToString());
                }
                getlistGroup(listMediaLib);
            }
            else if (checkNode.Level == 1)
            {
                foreach (TreeNode node in checkNode.Nodes) listMediaLib.Add(node.Name.ToString());
                getlistGroup(listMediaLib);
            }
            else if (checkNode.Level == 2)
            {
                listMediaLib.Add(checkNode.Name.ToString());
                getlistGroup(listMediaLib);
            }
        }

        #endregion

        #region get list album
        public void resetAlbum()
        {
            foreach (object obj in listGallary)
            {
                GalleryControl gc = (GalleryControl)obj;
                gc.Gallery.Groups.Clear();
            }
        }
        public void getListImage(string _colID = "0")
        {

            resetAlbum();
            string query_tblMediaLib = "SELECT * FROM tblMediaLib ";
            string query_tblMedia = "SELECT * FROM tblMedia ";
            if (_colID != "0")
            {
                query_tblMediaLib = query_tblMediaLib + " WHERE stt = " + _colID;
                query_tblMedia = query_tblMedia + " WHERE chuyende_id = " + _colID;
            }
            DataTable dt_tblMediaLib = sql.returnDB(query_tblMediaLib);
            DataTable dt_tblMedia = sql.returnDB(query_tblMedia);
            getAll_Album(dt_tblMediaLib, dt_tblMedia);
        }
        public void getlistGroup(ArrayList _colID)
        {
            string query_tblMediaLib = "SELECT * FROM tblMediaLib ";
            string query_tblMedia = "SELECT * FROM tblMedia ";
            if (_colID.Count > 0)
            {
                string idSTT = null;
                foreach (string id in _colID)
                {
                    idSTT += id + ",";
                }
                idSTT = idSTT.Substring(0, idSTT.Length - 1);
                query_tblMediaLib = query_tblMediaLib + " WHERE stt IN  (" + idSTT + ")";
                query_tblMedia = query_tblMedia + " WHERE chuyende_id IN  (" + idSTT + ")";
                DataTable dt_mediaLib = sql.returnDB(query_tblMediaLib);
                DataTable dt_media = sql.returnDB(query_tblMedia);
                getAll_Album(dt_mediaLib, dt_media);
            }


        }
        public void getAll_Album(DataTable _dtMediaLib, DataTable _dtMedia)
        {
            if (_dtMediaLib != null && _dtMedia != null)
            {
                int co_tblMediaLib = _dtMediaLib.Rows.Count;
                int co_tblMedia = _dtMedia.Rows.Count;
                foreach (object obj in listGallary)
                {
                    GalleryControl gc = (GalleryControl)obj;
                    for (int z = 0; z < co_tblMediaLib; z++)
                    {

                        GalleryItemGroup galleryItemGroup = new GalleryItemGroup();
                        galleryItemGroup.Caption = _dtMediaLib.Rows[z]["ten_chuyende"].ToString();
                        galleryItemGroup.Tag = _dtMediaLib.Rows[z]["stt"].ToString();
                        gc.Gallery.Groups.Add(galleryItemGroup);

                    }
                }

                //foreach (object obj in listGallary)
                for (int z = 0; z < listGallary.Count; z++)
                {
                    GalleryControl gc = (GalleryControl)listGallary[z];
                    string name = gc.Name.ToString();

                    Console.WriteLine("----" + gc.Name);
                    int conGroup = gc.Gallery.Groups.Count;
                    for (int y = 0; y < conGroup; y++)
                    {
                        string tagName = gc.Gallery.Groups[y].Tag.ToString();

                        for (int i = 0; i < co_tblMedia; i++)
                        {
                            if (tagName == _dtMedia.Rows[i]["chuyende_id"].ToString())
                            {
                                if (_dtMedia.Rows[i]["mediatype_id"].ToString() == name)
                                {
                                    string duoi = _dtMedia.Rows[i]["duoifile"].ToString();
                                    int dfile = Helping_Functions.returnFile(duoi);
                                    Console.WriteLine("----- la file : " + dfile);
                                    byte[] bytes = (byte[])_dtMedia.Rows[i]["media"];
                                    if (dfile == 1)
                                    {

                                        Image img = convert(bytes);
                                        GalleryItem gle = new GalleryItem();
                                        gle.Image = img;
                                        gle.Caption = _dtMedia.Rows[i]["ten_media"].ToString();
                                        gle.Tag = _dtMedia.Rows[i]["stt"].ToString();
                                        gc.Gallery.Groups[y].Items.Add(gle);
                                        Console.WriteLine("---- ID : " + _dtMedia.Rows[i]["stt"].ToString() + " ---- Gc : " + gc.Name);
                                    }
                                    else if (dfile > 1)
                                    {
                                        GalleryItem gle = new GalleryItem();
                                        gle.Image = global::SMART_VIET_V01.Properties.Resources.quanlyMedia_video;
                                        gle.Tag = _dtMedia.Rows[i]["stt"].ToString();
                                        gle.Caption = _dtMedia.Rows[i]["ten_media"].ToString();
                                        gc.Gallery.Groups[y].Items.Add(gle);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public Image convert(byte[] _byte)
        {
            Image newImage;
            using (MemoryStream stream = new MemoryStream(_byte))
            {
                newImage = System.Drawing.Image.FromStream(stream);
            }
            return newImage;
        }
        public SoundPlayer convertVideo(byte[] _byte)
        {
            SoundPlayer myPlayer;
            using (MemoryStream stream = new MemoryStream(_byte))
            {
                myPlayer = new SoundPlayer(stream);
                //Console.WriteLine(myPlayer.Site.Name.ToString());
            }
            return myPlayer;
        }

        #endregion

        #region insert delete
        public void insertItem()
        {
            Hashtable myHash = new Hashtable();
            string album = trView.Controls[0].Text.Trim();
            if (string.IsNullOrEmpty(album)) album = "New Album";
            string idFK = "0";
            string table = "tblKhoiLop";
            string colName = "ten_khoilop";
            if (trView.SelectedNode.Level > 0)
            {
                idFK = trView.SelectedNode.Parent.Name.ToString();
                if (trView.SelectedNode.Level == 1)
                {
                    table = "tblMonHoc";
                    colName = "ten_monhoc";
                    myHash["khoilop_id"] = idFK;//1
                }
                else
                {
                    table = "tblMediaLib";
                    colName = "ten_chuyende";
                    myHash["monhoc_id"] = idFK;
                }
            }
            myHash[colName] = album;
            int y = sql.SQLInsert(myHash, table);
            if (y > 0)
            {
                Console.WriteLine("---- Album : " + album);
                trView.SelectedNode.Text = album;
                trView.SelectedNode.Name = sql.returnID(table, "colID");
            }
        }

        public int updateName(int lv, string text)
        {

            string table = "tblMediaLib";
            string colName = "ten_chuyende";
            string colNameSet = "stt";
            if (lv == 0)
            {
                table = "tblKhoiLop";
                colName = "ten_khoilop";
                colNameSet = "stt";
            }
            else if (lv == 1)
            {
                table = "tblMonHoc";
                colName = "ten_monhoc";
                colNameSet = "stt";
            }
            string query = "UPDATE " + table + " SET " + colName + "  = @name WHERE " + colNameSet + " = " + trView.SelectedNode.Name.ToString();
            int y = sql.updateDK(query, "@name", text);
            return y;
        }
            
        public void deleteItem()
        {
            DialogResult res = MessageBox.Show("Bạn có muốn xóa thư viện hình ảnh này không?", "Xác nhận",
                                                              MessageBoxButtons.YesNo,
                                                              MessageBoxIcon.Question,
                                                              MessageBoxDefaultButton.Button2);
            if (res == DialogResult.Yes)
            {
                int lv = trView.SelectedNode.Level;
                string table = "tblMediaLib";
                if (lv == 0) table = "tblKhoiLop";
                else if (lv == 1) table = "tblMonHoc";
                string query = "DELETE FROM " + table + " WHERE stt = @sttID";
                int y = sql.updateDK(query, "@sttID", trView.SelectedNode.Name.ToString());
                if (y > 0) trView.SelectedNode.Remove();
            }
        }
        #endregion

        #region Textbox --> TreeView
        string textTmp;
        public TextBox addTextBox(int left, int top, int width, string text, bool isAddnew = false)
        {
            TextBox txt = new TextBox();
            txt.Text = text;
            txt.Width = 100;
            txt.Height = 20;
            string isUpdate = "update";
            txt.Location = new Point(left, top - (5 / 2));
            if(isAddnew) isUpdate = "insert";
            txt.Name = isUpdate;
            txt.Leave += new System.EventHandler(txtLeave);
            txt.KeyDown += new System.Windows.Forms.KeyEventHandler(txtKeyDown);
            return txt;
        }

        private void txtLeave(object sender, EventArgs e)
        {
            TextBox txt = (TextBox)sender;
            if (txt.Name == "update")
            {
                trView.HideSelection = false;
                trView.Controls.Clear();
                if (updateName(trView.SelectedNode.Level, txt.Text.Trim()) > 0) { trView.SelectedNode.Text = txt.Text.Trim(); }
                else { trView.SelectedNode.Text = textTmp; }
            }
            else
            {
                if (!string.IsNullOrEmpty(txt.Text.Trim()) || txt.Text.Trim() != "New Album") insertItem();
                else trView.SelectedNode.Remove();
                trView.Controls.RemoveAt(0);
            }
        }
        private void txtKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextBox txt = (TextBox)sender;
                if (txt.Name == "update")
                {
                    trView.HideSelection = false;
                    trView.Controls.Clear();
                    if (updateName(trView.SelectedNode.Level, txt.Text.Trim()) > 0) { trView.SelectedNode.Text = txt.Text.Trim(); }
                    else { trView.SelectedNode.Text = textTmp; }
                }
                else
                {
                    if (!string.IsNullOrEmpty(txt.Text.Trim())) insertItem();
                    else trView.SelectedNode.Remove();
                    trView.Controls.RemoveAt(0);
                }
            }
        }
        
        #endregion





        #region btn Action
        private void btnDelAlbum_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            trView_Leave(null, null);
            if (trView.SelectedNode != null) deleteItem();
        }

        public void addTreeNode(TreeNode trNode, int lv = 1)
        {
            trNode.Nodes.Add("New Album");
            trNode.Expand();
            trNode.Nodes[trNode.Nodes.Count - 1].ImageIndex = lv;
            trView.SelectedNode = trNode.Nodes[trNode.Nodes.Count - 1];
        }
        public void addTrView()
        {
            
            TreeNode trNodeChked = trView.SelectedNode;
            if (trNodeChked != null)
            {
                int index = trNodeChked.Index;
                if (trNodeChked.Level == 0) addTreeNode(trNodeChked);
                else if (trNodeChked.Level == 1) addTreeNode(trNodeChked, 2);
                else if (trNodeChked.Level == 2) addTreeNode(trNodeChked.Parent, 2);
            }
            else
            {
                trView.Nodes.Add("New Album");
                trView.Nodes[trView.Nodes.Count - 1].ImageIndex = 0;
                trView.SelectedNode = trView.Nodes[trView.Nodes.Count - 1];
            }
            try
            {
                trNodeChked = trView.SelectedNode;
                textTmp = trNodeChked.Text;
                TextBox txt = addTextBox(trNodeChked.Bounds.X, trNodeChked.Bounds.Y, trNodeChked.Bounds.Width, textTmp, true);
                trView.HideSelection = true;
                trView.Controls.Add(txt);
                txt.Focus();
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }
        }
        private void btnAddAlbum_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            trView_Leave(null, null);
            if (trView.Controls.Count == 0) addTrView();
           
        }

        public Hashtable getPostForm(bool isImages = true)
        {
            Hashtable myInfor = new Hashtable();
            myInfor["chuyende_id"] = trView.SelectedNode.Name.ToString();
            if (isImages)
                myInfor["mediatype_id"] = tabControl.SelectedTabPage.Name;

            return myInfor;
        }

        private void btnAddImage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (trView.SelectedNode != null)
            {
                if (trView.SelectedNode.Level == 2)
                {
                    openFileDialog1.Filter = "PNG Files (*.png)|*.png|" +
                        "Bitmap Files (*.bmp,*.dib)|*.bmp;*dib|" +
                        "JPEG Files (*.jpg,*.jpeg,*.jpe,*.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif|" +
                        "GIF Files (*.gif)|*.gif|TIFF Files (*.tif,*.tiff)|*.tif;*.tiff|" +
                        "All Images Type|*.png;*.bmp;*dib;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.tif;*.tiff";
                    openFileDialog1.FileName = "";
                    openFileDialog1.Title = "Sao lưu hình ảnh";
                    DialogResult result = openFileDialog1.ShowDialog();

                    if (result == DialogResult.OK)
                    {

                        foreach (string file in openFileDialog1.FileNames)
                        {
                            FileInfo fileInfor = new FileInfo(file);
                            string fileName = fileInfor.Name;
                            string[] strings = file.Split('.');
                            string duoi = strings[strings.Length - 1].ToString().ToLower();
                            Hashtable myMedia = getPostForm();
                            myMedia["ten_media"] = fileName;
                            myMedia["duoifile"] = duoi;
                            sql.insertMedia(myMedia, "tblMedia", "media", file);
                        }
                        trView_AfterSelect(null, null);
                    }
                }
                else MessageBox.Show("Vui lòng chọn chuyên đề.");
            }
            else MessageBox.Show("Vui lòng chọn chuyên đề.");
        }

        private void btnAddVideo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (trView.SelectedNode != null)
            {
                if (trView.SelectedNode.Level == 2)
                {
                    openFileDialog1.Filter = "Windows Media file (*.asf)|*.asf|" +
                                             "Windows Video file (*.avi)|*.avi|" +
                                             "MP4 Video file (*.mp4,*.m4v,*.mov)|*.mp4;*.m4v;*.mov|" +
                                             "Movie file (*.mpg,*.mpeg)|*.mpg;*.mpeg|" +
                                             "Adobe Flash Media (*.swf)|*.swf|" +
                                             "Windows Media Video file (*.wmv)|*.wmv|" +

                                             "AIFF Audio file (*.aiff)|*.aiff|" +
                                             "AU Audio file (*.au)|*.au|" +
                                             "MIDI file (*.mid,*.midi)|*.mid;*.midi|" +
                                             "MP3 Audio file (*.mp3)|*.mp3|" +
                                             "MPEG-4 Audio file (*.m4a,*.mp4)|*.m4a;*.mp4|" +
                                             "Windows Audio file (*.wav)|*.wav|" +
                                             "Windows Media Audio file (*.wma)|*.wma|" +
                                             "All Videos Type |*.asf;*.avi;*.mp4;*.m4v;*.mov;*.mpg;*.mpeg;*.swf;*.wmv;*.aiff;*.au;*.mid;*.midi;*.mp3;*.m4a;*.mp4;*.wav;*.wma";
                    openFileDialog1.FileName = "";
                    openFileDialog1.Title = "Sao lưu Videos";
                    DialogResult result = openFileDialog1.ShowDialog();

                    if (result == DialogResult.OK)
                    {
                        foreach (string file in openFileDialog1.FileNames)
                        {
                            FileInfo fileInfor = new FileInfo(file);
                            string fileName = fileInfor.Name;
                            string[] strings = file.Split('.');

                            string duoi = strings[strings.Length - 1].ToString().ToLower();
                            Hashtable myMedia = getPostForm();
                            myMedia["ten_media"] = fileName;
                            myMedia["duoifile"] = duoi;
                            sql.insertMedia(myMedia, "tblMedia", "media", file);
                        }
                        trView_AfterSelect(null, null);
                    }
                }
                else MessageBox.Show("Vui lòng chọn chuyên đề.");
            }
            else MessageBox.Show("Vui lòng chọn chuyên đề.");
        }

        private void btnDelVideo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string text = "Bạn có muốn xóa những mục đã chọn này không?";
            deleteItemGallary(text);


        }

        private void btnDelImage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string name = tabControl.SelectedTabPage.Name;
            foreach (object obj in listGallary)
            {
                GalleryControl gc = (GalleryControl)obj;
                if (gc.Name == name)
                {
                    for (int i = 0; i < gc.Gallery.Groups.Count; i++)
                    {
                        foreach (GalleryItem item in gc.Gallery.Groups[i].Items)
                        {
                            item.Checked = true;
                        }
                    }
                    break;
                }

            }
            deleteItemGallary("Bạn có muốn xóa toàn bộ hình ảnh và video không?");
        }

        public void deleteItemGallary(string text)
        {
            button1_Click(null, null);
            string name = tabControl.SelectedTabPage.Name;
            foreach (object obj in listGallary)
            {
                GalleryControl gc = (GalleryControl)obj;
                if (gc.Name == name)
                {
                    int count = gc.Gallery.Groups.Count;
                    List<GalleryItem> items = gc.Gallery.GetCheckedItems();
                    if (items.Count > 0)
                    {
                        DialogResult res = MessageBox.Show(text, "Xác nhận",
                                                                     MessageBoxButtons.YesNo,
                                                                     MessageBoxIcon.Question,
                                                                     MessageBoxDefaultButton.Button2);
                        if (res == DialogResult.Yes)
                        {
                            string query = "DELETE FROM tblMedia WHERE stt = @sttID";
                            foreach (GalleryItem item in items) sql.updateDK(query, "@sttID", item.Tag.ToString());
                            trView_AfterSelect(null, null);
                        }
                    }
                    else MessageBox.Show("Vui lòng chọn file cần xóa!");
                    break;
                }
            }
        }

        #endregion


        private void trView_MouseDown(object sender, MouseEventArgs e)
        {
            if (trView.HitTest(e.Location).Node == null) { trView.SelectedNode = null; getListImage(); }
        }

        private void trView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F2)
            {
                try
                {
                    textTmp = trView.SelectedNode.Text;
                    TextBox txt = addTextBox(trView.SelectedNode.Bounds.X, trView.SelectedNode.Bounds.Y, trView.SelectedNode.Bounds.Width, textTmp);
                    trView.HideSelection = true;
                    trView.SelectedNode.Text = "";
                    trView.Controls.Add(txt);
                    txt.Focus();
                }
                catch (Exception ex) { Console.WriteLine(ex.Message); }
            }
            else if (e.KeyCode == Keys.Delete)
            {
                deleteItem();
            }

        }

        private void trView_Leave(object sender, EventArgs e)
        {
            if (trView.Controls.Count > 0)
            {
                //TextBox txt = (TextBox)trView.Controls[0];
                //txtLeave(txt, null);
                //trView.SelectedNode = null;
                trView.Controls.RemoveAt(0);
            } 
        }








    }
}
